package com.zyd.shiro.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Auth: zorpan
 * 2019.1.25 18:30
 * 七牛云图片工具，采用注解方式注入util，然后按照普通类调用函数，
 * get方法返回的是图片的私有加签地址，put方法返回文件hash值，同时默认为文件名
 * 需要注意的，一些参数采用读取配置文件，正确使用需要在配置文件中加入以下配置
 * qiniu:
 *     AccessKey: Bkk5JghsxYW1BryjI08SBwMqKIrH1cQlSO_ACEiI
 *     SecretKey: vWv9bxU9MkSo4PazfkN0hrwku8Se9c8723NcdC8b
 *     Bucket: hlmall
 *     Host: http://plvq1w9bx.bkt.clouddn.com
 */
public class QiniuUtil {
    @Autowired
    private UploadManager uploadManager;
    @Autowired
    private Auth auth;
    @Value("${qiniu.Bucket}")
    private String bucket;

    @Value("${qiniu.Host}")
    private String host;

    @Autowired
    private Gson gson;


    /**
     * 上传图片到七牛
     * @param inputStream 图片的输入流
     * @return 文件hash即文件名
     * @throws QiniuException
     */
    public String putFile(InputStream inputStream) throws QiniuException {
        Response response = this.uploadManager.put(inputStream, null, getUploadToken(), null, null);
        int retry = 0;
        while (response.needRetry() && retry < 3) {
            response = this.uploadManager.put(inputStream, null, getUploadToken(), null, null);
            retry++;
        }
        DefaultPutRet putRet = gson.fromJson(response.bodyString(), DefaultPutRet.class);
        return host+putRet.hash;
    }

    /**
     * 获取七牛云文件的私有地址
     * @param fileName 文件名
     * @return 图片私有链接，默认有效时间一小时
     * @throws UnsupportedEncodingException
     */
    public String getFile(String fileName) throws UnsupportedEncodingException {
        return fileName;
        /**String encodedFileName = URLEncoder.encode(fileName, "utf-8");
        String publicUrl = String.format("%s/%s", this.host, encodedFileName);
        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
        String finalUrl = this.auth.privateDownloadUrl(publicUrl, expireInSeconds);
        return finalUrl;*/
    }


    /**
     * 获取上传凭证
     *
     * @return
     */
    private String getUploadToken() {
        return this.auth.uploadToken(this.bucket);
    }

}
